/**
 * @constructor 编辑库名称
 */
import React from 'react';
import { Form, Input, Field, Overlay, Balloon } from '@teamix/ui';
import { YunxiaoIcon } from '@alife/devops-ui';
import GroupSelect from 'components/groupSelect';
import { checkImportProjectName } from 'api/index.js';
import './overlay.scss';
import intl from '../../locale';

const { organization } = window.FORCE;

const prefix = 'new-import-name';
const FormItem = Form.Item;
const formItemLayout = {
  labelCol: {
    span: 6,
  },

  wrapperCol: {
    span: 14,
  },
};

const validateCodeMap = {
  400: intl.get({
    id: 'code-assets.components.importProjectListModal.overlay1.Invalid',
    defaultMessage: '不合法',
  }),
  409: intl.get({
    id: 'code-assets.components.importProjectListModal.overlay1.AlreadyExists',
    defaultMessage: '已存在',
  }),
  403: intl.get({
    id: 'code-assets.components.importProjectListModal.overlay1.NoPermission',
    defaultMessage: '无权限',
  }),
  default: intl.get({
    id: 'code-assets.components.importProjectListModal.overlay1.Error',
    defaultMessage: '错误',
  }),
};

export default class TableCellOverlay extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      visible: false,
      // groupPath: '',
      // 没有namespaceId显示文字
      namespacePlaceholder: intl.get({
        id: 'code-assets.components.importProjectListModal.overlay1.DoNotSelectAGroup',
        defaultMessage: '不选择分组',
      }),
      groupAccess: '',
      offsetState: '',
    };

    this.field = new Field(this);
  }

  onClick = () => {
    const { invalidInfo, notAllowValidModify } = this.props;
    if (notAllowValidModify) {
      if (!invalidInfo) {
        return;
      }
    }

    const { visible } = this.state;

    this.setState({
      visible: !visible,
      offsetState:
        invalidInfo &&
        (invalidInfo.status === 403 || invalidInfo.status === 409 || invalidInfo.status === 400),
    });

    // 403 代码组飘红 409 代码库飘红 400 代码库和组都飘红
    if (invalidInfo) {
      if (invalidInfo.status === 403) {
        this.field.setError('namespace_id', invalidInfo.text);
      } else if (invalidInfo.status === 409) {
        this.field.setError('path', invalidInfo.text);
      } else {
        this.field.setError('namespace_id', invalidInfo.text);
        this.field.setError('path', invalidInfo.text);
      }
    } else {
      this.field.setError('namespace_id', '');
      this.field.setError('path', '');
    }
  };

  onClose = () => {
    const { groupAccess } = this.state;
    const { namespace_id, path } = this.field.getValues();
    const { is_group_required } = this.props;
    // 没有path，直接关闭
    if (!path) {
      this.setState({
        visible: false,
      });

      return;
    }
    if (is_group_required && !namespace_id) {
      this.setState({
        visible: false,
      });

      return;
    }
    this.checkPath(path, (error) => {
      if (!error) {
        const saveName = this.getRealPath();
        this.props.saveName(saveName, this.props.import_repo_id, groupAccess);
      }
      this.setState({
        visible: false,
      });
    });
  };

  onVisibleChange = (visible) => {
    this.setState({
      visible,
    });
  };

  pathValidator = (rule, value, callback) => {
    const { is_group_required } = this.props;
    if (!value) {
      callback();
    } else if (!this.field.getValue('path')) {
      callback(
        intl.get({
          id: 'code-assets.components.importProjectListModal.overlay1.TheDatabasePathIsRequired',
          defaultMessage: '库路径是必填项，请修改',
        }),
      );
    } else if (is_group_required && !this.field.getValue('namespace_id')) {
      callback(
        intl.get({
          id: 'code-assets.components.importProjectListModal.overlay1.TheGroupPathIsRequired',
          defaultMessage: '组路径是必填项，请修改',
        }),
      );
    } else {
      this.checkPath(value, callback);
    }
  };

  getRealPath = () => {
    const { namespace_id, path } = this.field.getValues();
    return namespace_id && namespace_id !== this.state.namespacePlaceholder
      ? `${namespace_id.trim()}/${path.trim()}`
      : path.trim();
  };

  checkPath = (value, callback) => {
    // path传group + message; namespa_id:企业namespace_id
    const org_namespace_id = organization.namespace_id || '';
    const curValue = this.getRealPath();
    const { visibility_level } = this.props;
    checkImportProjectName({
      path: curValue,
      name: '',
      namespace_id: org_namespace_id,
      visibility_level,
    })
      .then(() => {
        this.field.setError('path', '');
        this.field.setError('namespace_id', '');
        callback();
        this.setState({ offsetState: false });
      })
      .catch((err) => {
        const errCause = JSON.parse(err.responseText).cause;
        callback(`${errCause}`);
        this.setState({ offsetState: true });
      });
  };

  onKeyDown = (e) => {
    if (e.keyCode === 13) {
      this.onClose();
    }
  };

  handleValue = () => {
    const { value } = this.props;
    if (!value) {
      return {
        path: '',
        namespaceId: '',
      };
    }
    if (!value.includes('/')) {
      return {
        path: value.trim(),
        namespaceId: '',
      };
    }
    const arr = value.split('/');
    const path = arr.splice(arr.length - 1, 1)[0];
    return {
      path: path.trim(),
      namespaceId: arr.join('/').trim(),
    };
  };

  setPathWithNamespace = (value, item) => {
    this.setState({
      groupAccess: item && item.visibility_level ? item.visibility_level : '',
    });
  };

  render() {
    const { invalidInfo, value, import_repo_id, is_group_required, notAllowValidModify } =
      this.props;
    const { namespacePlaceholder } = this.state;

    const { path, namespaceId } = this.handleValue();

    const { init } = this.field;
    let errorText;
    if (invalidInfo) {
      errorText =
        invalidInfo.text || validateCodeMap[invalidInfo.status] || validateCodeMap.default;
    } else {
      errorText = '';
    }
    return (
      <div className={`${prefix}-cellbody`}>
        <div
          className={`${prefix}-cell`}
          ref={(ref) => {
            this.target = ref;
          }}
        >
          <div className={`${prefix}-cell-body ${invalidInfo ? 'has-error' : ''}`}>
            <Balloon.Tooltip
              trigger={<span className={`${prefix}-cell-info one-line-ellipsis`}>{value}</span>}
              align="t"
            >
              {value}
            </Balloon.Tooltip>
          </div>
          <div
            className={`${prefix}-cell-help`}
            style={{ display: invalidInfo ? 'block' : 'none' }}
          >
            <YunxiaoIcon type="delete-fill" style={{ fontSize: 14 }} /> {errorText}
          </div>
        </div>
        <div
          className={`${prefix}-cell-edit`}
          onClick={this.onClick}
          ref={(ref) => {
            this.btn = ref;
          }}
        >
          <YunxiaoIcon
            className="edit-name-icon"
            type="edit-line"
            style={{ display: invalidInfo || !notAllowValidModify ? 'block' : 'none' }}
          />
        </div>
        <Overlay
          visible={this.state.visible}
          target={this.target ? this.target.parentNode.parentNode.parentNode : this.target}
          safeNode={[() => this.select, () => this.btn]}
          container={() => this.target}
          onRequestClose={this.onClose}
          align="tl tl"
          offset={this.state.offsetState ? [0, -30] : [0, 0]}
          shouldUpdatePosition
        >
          <div
            style={
              (this.field.getError('path') || this.field.getError('namespace_id')) && {
                marginTop: '30px',
              }
            }
            className={`${prefix}-edit-area overlay-shadow ${
              this.field.getError('path') || this.field.getError('namespace_id') ? 'has-error' : ''
            }`}
            onKeyDown={this.onKeyDown}
          >
            <Form {...formItemLayout} autoComplete="off" field={this.field} labelAlign="top">
              <div className={`${prefix}-edit-area-items import_repo_id_${import_repo_id}`}>
                <FormItem
                  label=" "
                  className="namespace_id"
                  help={
                    this.field.getError('path') || this.field.getError('namespace_id') ? (
                      <div className="next-form-item-help path-error-help">
                        <YunxiaoIcon type="delete-fill" />
                        <span className="next-form-item-help-text">
                          {this.field.getError('path') || this.field.getError('namespace_id')}
                        </span>
                      </div>
                    ) : (
                      ''
                    )
                  }
                >
                  <GroupSelect
                    autoComplete
                    {...init('namespace_id', {
                      initValue: namespaceId || namespacePlaceholder,
                      rules: is_group_required
                        ? [
                            {
                              required: true,
                              message: intl.get({
                                id: 'code-assets.components.importProjectListModal.overlay1.GroupIsRequiredModify',
                                defaultMessage: '组是必填项,请修改',
                              }),
                            },
                            {
                              validator: this.pathValidator,
                            },
                          ]
                        : [
                            {
                              validator: this.pathValidator,
                            },
                          ],
                    })}
                    okFn={this.setPathWithNamespace}
                    style={{ width: '100%' }}
                    popupContainer={(t) => t}
                    ref={(ins) => {
                      this.select = ins;
                    }}
                  />
                </FormItem>
                <span className="split">/</span>
                <FormItem label=" " className="path" help="">
                  <Input
                    placeholder={intl.get({
                      id: 'code-assets.components.importProjectListModal.overlay1.EnterAnAddress',
                      defaultMessage: '请输入地址',
                    })}
                    {...init('path', {
                      rules: [
                        {
                          required: true,
                          message: intl.get({
                            id: 'code-assets.components.importProjectListModal.overlay1.TheDatabasePathIsRequired',
                            defaultMessage: '库路径是必填项，请修改',
                          }),
                        },

                        {
                          validator: this.pathValidator,
                        },
                      ],

                      initValue: path,
                    })}
                  />
                </FormItem>
              </div>
            </Form>
          </div>
        </Overlay>
      </div>
    );
  }
}
